<script setup lang="ts">
import { computed, onMounted, ref, shallowRef } from 'vue';
import { $t } from '@/locales';
import { type AreaTreeSearchParams, fetchAllProvList, fetchAreaByIp } from '@/service/api';
import { useBoolean } from '~/packages/hooks/src';
import { isValidIP } from '@/utils/common';

defineOptions({
  name: 'AreaSearch'
});

interface Emits {
  (e: 'reset'): void;
  (e: 'search'): void;
}

const emit = defineEmits<Emits>();

const { bool: ipSearchVisible, setTrue: openIpSearchModel, setFalse: closeIpSearchModel } = useBoolean();

const model = defineModel<AreaTreeSearchParams>('model', { required: true });

const areaProvOptions = shallowRef<Api.Common.Options[]>([]);

const ip = ref();
const ipAddress = ref();

const ipValidationStatus = computed(() => {
  return createIpValidationStatus(ip.value);
});

const ipFeedback = computed(() => {
  return createFeedback(ip.value);
});

function createIpValidationStatus(value: string) {
  if (!value || value === null || value === undefined || value === '') {
    return 'error';
  }
  const ipArr: string[] = value.split(',');
  let flag = true;
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < ipArr.length; i++) {
    if (!isValidIP(ipArr[i])) {
      flag = false;
      break;
    }
  }
  if (!flag) {
    return 'error';
  }
  return undefined;
}

function createFeedback(value: string) {
  if (!value || value === null || value === undefined || value === '') {
    return $t('form.required');
  }
  const ipArr: string[] = value.split(',');
  let flag = true;
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < ipArr.length; i++) {
    if (!isValidIP(ipArr[i])) {
      flag = false;
      break;
    }
  }
  if (!flag) {
    return $t('page.manage.area.ipCheckFail');
  }
  return undefined;
}

async function getAreaProvOptions() {
  const { data: res } = await fetchAllProvList();
  if (!res) return;
  res.forEach(item => {
    areaProvOptions.value.push({
      label: item.name,
      value: item.id,
      extra: ''
    });
  });
}

function reset() {
  emit('reset');
}

function search() {
  emit('search');
}

function handleIpSearchModal() {
  ip.value = null;
  ipAddress.value = null;
  openIpSearchModel();
}

function handleIpSearchCanel() {
  ip.value = null;
  ipAddress.value = null;
  closeIpSearchModel();
}

async function handleIpSearch() {
  if (!ip.value) return;
  const { data, error } = await fetchAreaByIp(ip.value);
  if (!error) {
    ipAddress.value = data;
  }
}

onMounted(() => {
  getAreaProvOptions();
});
</script>

<template>
  <NCard :title="$t('common.search')" :bordered="false" size="small" class="card-wrapper">
    <NForm :model="model" label-placement="left" :label-width="80">
      <NGrid responsive="screen" item-responsive>
        <NFormItemGi span="24 s:12 m:6" :label="$t('page.manage.area.name')" path="name" class="pr-24px">
          <NSelect
            v-model:value="model.id"
            :options="areaProvOptions"
            :placeholder="$t('page.manage.area.form.name')"
            key-field="value"
          />
        </NFormItemGi>
        <NFormItemGi span="24 s:12 m:6">
          <NSpace class="w-full" justify="end">
            <NButton @click="reset">
              <template #icon>
                <icon-ic-round-refresh class="text-icon" />
              </template>
              {{ $t('common.reset') }}
            </NButton>
            <NButton type="primary" ghost @click="search">
              <template #icon>
                <icon-ic-round-search class="text-icon" />
              </template>
              {{ $t('common.search') }}
            </NButton>
            <NButton type="info" ghost @click="handleIpSearchModal">
              <template #icon>
                <icon-mdi:ip-network-outline class="text-icon" />
              </template>
              {{ $t('page.manage.area.ipSearch') }}
            </NButton>
          </NSpace>
        </NFormItemGi>
      </NGrid>
    </NForm>
    <!-- @vue-ignore -->
    <NModal
      v-model:show="ipSearchVisible"
      :title="$t('page.manage.area.ipSearch')"
      preset="card"
      class="w-150"
      style="position: fixed; top: 20%; left: 50%; transform: translate(-50%, -50%)"
    >
      <NScrollbar class="pr-20px">
        <NFormItem
          label="IP"
          label-placement="left"
          label-width="80px"
          show-require-mark
          :validation-status="ipValidationStatus"
          :feedback="ipFeedback"
        >
          <NInput v-model:value="ip" :placeholder="$t('page.manage.area.form.ipSearch')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.area.ipAddress')" label-placement="left" label-width="80px">
          <NInput v-model:value="ipAddress" type="textarea" :placeholder="$t('page.manage.area.form.ipAddress')" />
        </NFormItem>
        <NFormItem>
          <NSpace class="w-full" justify="end">
            <NButton @click="handleIpSearchCanel">
              <template #icon>
                <icon-ic-round-refresh class="text-icon" />
              </template>
              {{ $t('common.cancel') }}
            </NButton>
            <NButton type="primary" ghost @click="handleIpSearch">
              <template #icon>
                <icon-ic-round-search class="text-icon" />
              </template>
              {{ $t('common.confirm') }}
            </NButton>
          </NSpace>
        </NFormItem>
      </NScrollbar>
    </NModal>
  </NCard>
</template>

<style scoped></style>
